package com.datatheorem.ohos.trustkit.demoapp.slice;

import ohos.aafwk.ability.delegation.AbilityDelegatorRegistry;

import com.datatheorem.ohos.trustkit.TrustKit;
import com.datatheorem.ohos.trustkit.config.RegexValidator;

import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

import junit.framework.TestCase;

import static org.junit.Assert.*;
import static org.junit.Assert.assertTrue;

public class DemoMainAbilitySliceTest {
    String testUrl = "https://www.datatheorem.com";
    // Regular expression strings for hostnames (derived from RFC2396 and RFC 1123)
    // RFC2396: domainlabel   = alphanum | alphanum *( alphanum | "-" ) alphanum
    // Max 63 characters
    private static final String DOMAIN_LABEL_REGEX = "\\p{Alnum}(?>[\\p{Alnum}-]{0,61}\\p{Alnum})?";
    // RFC2396 toplabel = alpha | alpha *( alphanum | "-" ) alphanum
    // Max 63 characters
    private static final String TOP_LABEL_REGEX = "\\p{Alpha}(?>[\\p{Alnum}-]{0,61}\\p{Alnum})?";
    // RFC2396 hostname = *( domainlabel "." ) toplabel [ "." ]
    // Note that the regex currently requires both a domain label and a top level label, whereas
    // the RFC does not. This is because the regex is used to detect if a TLD is present.
    // If the match fails, input is checked against DOMAIN_LABEL_REGEX (hostnameRegex)
    // RFC1123 sec 2.1 allows hostnames to start with a digit
    private static final String DOMAIN_NAME_REGEX =
        "^(?:" + DOMAIN_LABEL_REGEX + "\\.)+" + "(" + TOP_LABEL_REGEX + ")\\.?$";
    /**
     * RegexValidator for matching domains.
     */
    private final RegexValidator domainRegex =
        new RegexValidator(DOMAIN_NAME_REGEX);
    /**
     * RegexValidator for matching a local hostname
     */
    // RFC1123 sec 2.1 allows hostnames to start with a digit
    private final RegexValidator hostnameRegex =
        new RegexValidator(DOMAIN_LABEL_REGEX);


    @Test
    public void onStart() {
        testConfiguration();
        testRegexValidator();
    }

    private void testRegexValidator() {
        boolean isHost =  hostnameRegex.isValid(testUrl);
        boolean isDomain =  domainRegex.isValid(testUrl);
        assertTrue(isHost);
        assertTrue(isDomain);
    }

    private void testConfiguration() {
        TrustKit.initializeWithNetworkSecurityConfiguration(AbilityDelegatorRegistry.getAbilityDelegator().getAppContext());
        try {
            URL url = new URL(testUrl);
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
            connection.setSSLSocketFactory(TrustKit.getInstance().getSSLSocketFactory(url.getHost()));
            assertTrue(true);
        } catch (MalformedURLException e) {
            e.printStackTrace();
            assertTrue(false);
        } catch (IOException e) {
            e.printStackTrace();
            assertTrue(false);
        }
    }
}